/*
 * @Descripttion: 
 * @Author: 银河以北
 * @Date: 2023-03-21 16:44:26
 * @LastEditors: 银河以北
 * @LastEditTime: 2023-03-23 20:30:51
 */
/**
 * 请求封装
 */
import blogSetting from "@/config/index";
export async function request({ url = '', data = {}, method = 'GET', type = 'fetch' }) {
    const baseUrl = "https://yinheyibei.serve.yinheyibei.cn/"
    method = method.toUpperCase();
    if (!url.includes('http')) {
        url = baseUrl + url;
    }

    // GET请求
    if (method == 'GET') {
        // 处理GET请求参数
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }

    // 判断浏览器是否兼容fetch
    if (window.fetch && type == 'fetch') {
        let requestConfig = {
            method,
            headers: {
                // 'Accept': 'application/json',
                // 'Content-Type': 'application/json'
                // 'Authorization':blogSetting.pexelsKey
            },
            mode: "cors",
            cache: "force-cache"
        }

        // POST PUT DELETE请求
        const RequireType = ['POST', 'PUT', 'DELETE']
        if (RequireType.includes(method)) {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }

        try {
            const response = await fetch(url, requestConfig);
            const responseJson = await response.json();
            return responseJson

        } catch (error) {
            throw new Error(error)
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }
            let sendData = '';
            if (method == 'POST') {
                sendData = JSON.stringify(data);
            }
            requestObj.open(method, url, true);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            // requestObj.setRequestHeader("Authorizatione", blogSetting.pexelsKey);
            requestObj.send(sendData);
            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}